package com.ruoyi.riskrule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.service.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.RiskConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.extdata.common.config.RuleConfig;
import com.ruoyi.extdata.service.IExternalApiService;
import com.ruoyi.riskrule.component.RaiseLimitComponent;
import com.ruoyi.riskrule.config.RaiseLimitParamsLoader;
import com.ruoyi.riskrule.config.Step1ParamsLoader;
import com.ruoyi.riskrule.config.Step2ParamsLoader;
import com.ruoyi.riskrule.config.common.RuleUtils;
import com.ruoyi.riskrule.domain.RuleInNextStepCrs;
import com.ruoyi.riskrule.domain.RuleInNextStepXds;
import com.ruoyi.riskrule.domain.RuleNextDto;
import com.ruoyi.riskrule.service.ICustomerCreditService;
import com.ruoyi.riskrule.service.ILoanFieldService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.*;


@Slf4j
@Service
@RequiredArgsConstructor
public class RuleEngineService {

    @Value("${server.run-env}")
    private String environment;

    private final Step1ParamsLoader step1ParamsLoader;

    private final Step2ParamsLoader step2ParamsLoader;

    private final IRuleInService ruleInService;

    private final RuleConfig ruleConfig;

    private final IRuleOutService ruleOutService;

    private final IRuleNodeResultService ruleNodeResultService;

    private final IRuleHitService ruleHitService;

    private final ICustomerCreditService customerCreditService;

    private final IRuleInNextStepService iRuleInNextStepService;

    private final IExternalApiService iExternalApiService;

    private final IRealNameAuthService iRealNameAuthService;

    private final INextStepXdsService iNextStepXdsService;

    private final INextStepCrsService iNextStepCrsService;

    private final RaiseLimitParamsLoader raiseLimitParamsLoader;

    private final IIncreasedLimitLogService increasedLimitLogService;

    private final ILoanOrderService iLoanOrderService;

    private final ILoanFieldService loanFieldService;

    private final RaiseLimitComponent raiseLimitComponent;

    private final ICustActiveIncreaseLogService activeIncreaseLogService;

    private final ILoanIouService iLoanIouService;

    private final ILoanIouDeferredService loanIouDeferredService;

    private final IProductDeferredInfoService productDeferredInfoService;
    private final ILoanFieldService loanService;


    public JSONObject riskRuleRaiseLimit(String ruleType, String customerNo) {
        log.info("客户号{}开始执行{}提额规则引擎", customerNo, ruleType);
        JSONObject riskParam = raiseLimitComponent.paramsAssembly(ruleType, customerNo);
        riskParam.put("runenv", environment);
        String apiName = "TD-" + ruleType;
        log.info("提额规则入参json:{}", riskParam.toJSONString());
        String apiResult = iExternalApiService.ruleRequest(riskParam, ruleConfig.getUrl() + ruleConfig.getLimitAdjustUrl2(), apiName);

        JSONObject resJson = this.analysisRuleOut(apiResult, customerNo, null, null, riskParam.getString("operType"));
        //产品需求 预备调用日志
        activeIncreaseLogService.saveLog(customerNo, ruleType, resJson);
        //解析结果并返回
        return resJson;
    }

    /**
     * 结清
     *
     * @param loanSerialNo
     * @param customerNo
     * @param ruleIn
     * @return
     */
    public JSONObject riskRuleRaiseLimit(String loanSerialNo, String customerNo, RuleIn ruleIn) {

        log.info("客户号{}借据{}开始执行提额规则引擎", customerNo, loanSerialNo);
        if (Func.isEmpty(ruleIn)) {
            ruleIn = raiseLimitParamsLoader.initRuleInParam(loanSerialNo, customerNo);
        }
        /**
         *  以下字段放在这里是考虑一个用户多笔结清的情况
         */
        //可用授信额度
        CreditAccount creditAccount = raiseLimitParamsLoader.getCreditAccount(customerNo);
        ruleIn.setCreditLine(creditAccount.getCreditLine().toString());

        //客户申请延期总次数
        int count = loanIouDeferredService.count(new QueryWrapper<LoanIouDeferred>().eq("cust_no", customerNo));
        ruleIn.setDeferredcnt(count == 0 ? "-1" : count + "");
        log.info("客户申请延期总次数:{}",count);

        //当前客户总延期天数
        int deferredTotalDay = loanIouDeferredService.getDeferredTotalDay(customerNo);
        ruleIn.setDeferredtotalday(deferredTotalDay == 0 ? "-1" : deferredTotalDay + "");

        //该客户历史和当前的最大逾期天数
        Integer maximumOverdue = loanService.getMaximumOverdue(customerNo);
        ruleIn.setMaxyuqitianshu((maximumOverdue == null ? 0 : maximumOverdue) + "");

        //当前客户申请延期的合同数
        Integer deferredhetong = iLoanIouService.getHaveDeIou(customerNo);
        ruleIn.setDeferredhetong(deferredhetong == 0 ? "-1" : deferredhetong + "");

        log.info("客户customerNo:{}", customerNo);
        //当前客户所有未结清合同的最近到期日
        String minDuedate = iLoanIouService.selectMinDueData(customerNo);
        String replace = "";
        if (minDuedate.contains("/")) {
            replace = minDuedate.replace("/", "-");
            replace = replace + " 00:00:00";
            ruleIn.setMinDuedate(replace);
        } else {
            ruleIn.setMinDuedate(minDuedate);
        }
        log.info("客户minDuedate:{}", minDuedate);
        log.info("rulein的minduedate:{}", ruleIn.getMinDuedate());

        //该客户当前的最大逾期天数，可为0
        Integer currentOverdue = loanService.getCurrentOverdue(customerNo);
        ruleIn.setCurrentmaxyuqi((currentOverdue == null ? 0 : currentOverdue) + "");

        //当前申请人结清利息
        String jieQingLiXi = loanIouDeferredService.getJieQingLiXi(customerNo);
        ruleIn.setJieqinglixi(jieQingLiXi);

        //当前申请人结清服务费
        String jieQingFuWuFei = loanIouDeferredService.getJieQingFuWuFei(customerNo);
        ruleIn.setJieqingfuwufei(jieQingFuWuFei);

        //originalline 客户首次成功授信时的额度
        IncreasedLimitLog increasedLimitLog = new IncreasedLimitLog();
        increasedLimitLog.setCustNo(customerNo);
        increasedLimitLog.setAdjustType(Constants.RaiseLimit.ADJUST_TYPE_INIT);
        List<IncreasedLimitLog> increasedLimitLogs = increasedLimitLogService.selectIncreasedLimitLogList(increasedLimitLog);
        if (increasedLimitLogs.size() > 0) {
            ruleIn.setOriginalline(increasedLimitLogs.get(0).getCurrentCreditLine() + "");
        }
        //autorised	因自动化提额流程提升的总额度
        increasedLimitLog.setAdjustType(Constants.RaiseLimit.ADJUST_TYPE_AUTOMATIC_ALLOCATION);
        increasedLimitLogs = increasedLimitLogService.selectIncreasedLimitLogList(increasedLimitLog);
        BigDecimal autorised = new BigDecimal(0);
        for (IncreasedLimitLog e : increasedLimitLogs) {
            autorised = autorised.add(e.getIncreasedAmt());
        }
        ruleIn.setAutorised(autorised + "");

        //获取客户所有的借据
        List<LoanIou> activeLoanList = loanFieldService.getLoanIouByCustNo(customerNo, null);
        BigDecimal zaidaibenjin = new BigDecimal(0);
        BigDecimal zaidaibenjin2 = BigDecimal.ZERO;

        for (LoanIou iou : activeLoanList) {
            if (iou.getIouStatus() == 0 || iou.getIouStatus() == 2) {
                zaidaibenjin2 = zaidaibenjin2.add(iou.getLoanPrincipal());
                zaidaibenjin = zaidaibenjin.add(iou.getLoanPrincipal().subtract(iou.getRepaidPrincipal()));
            }
        }
        BigDecimal ss = com.ruoyi.common.utils.StringUtils.isBlank(creditAccount.getCreditLine().toString()) ? BigDecimal.ZERO : new BigDecimal(creditAccount.getCreditLine().toString()).subtract(zaidaibenjin2);
        ruleIn.setRestofamt(raiseLimitParamsLoader.bigDecimalToString(ss));


        //risedinaday 一天内由自动化提额成功提升的额度之和。
        String risedinaday = increasedLimitLogService.getLineByNow(customerNo) + "";
        if (StringUtils.isBlank(risedinaday) || "null".equals(risedinaday)) {
            risedinaday = "0";
        }
        ruleIn.setRisedinaday(risedinaday);

        LoanOrder loanOrder = new LoanOrder();
        loanOrder.setLoanSerialNo(loanSerialNo);
        LoanOrder loanOrders = iLoanOrderService.selectLoanOrderList(loanOrder).get(0);
        ruleIn.setCurrentApplyLine(loanOrders.getLoanAmt() + "");
        ruleInService.insertRuleIn(ruleIn);

        JSONObject riskParam = RuleUtils.riskParamConversion(ruleIn);

        //当前运行环境
        riskParam.put("runenv", environment);
        String url = ruleConfig.getUrl() + ruleConfig.getLimitAdjustUrl();
        log.info("规则入参json:{}", riskParam.toJSONString());
        log.info("URL规则1入参json:{}", url);

        String apiResult = iExternalApiService.ruleRequest(riskParam, url, "apiName");

        ruleIn.setRecFlag(UserConstants.BUSINESS_NORMAL);
        ruleInService.updateRuleIn(ruleIn);
        return this.analysisRuleOut(apiResult, ruleIn.getCustNo(), ruleIn.getApplySerialNo(), ruleIn.getLoanSerialNo(), ruleIn.getOperType());

    }


    /**
     * 提现，授信申请规则
     *
     * @param applyType
     * @param serialNo
     * @return
     */
    public JSONObject riskRuleEngine(String applyType, String serialNo) {
        log.info("进入远程调用riskRuleEngine 已进入，applyType：{},  serialNo：{}", applyType, serialNo);
        //参数加工
        RuleIn ruleIn = step1ParamsLoader.initRuleInParam(applyType, serialNo);
        ruleInService.insertRuleIn(ruleIn);

        JSONObject riskParam = RuleUtils.riskParamConversion(ruleIn);
        //当前运行环境
        riskParam.put("runenv", environment);

        String url = ruleConfig.getUrl();
        String apiName = "";
        if (RuleConfig.RULE_TYPE_LOAN.equals(applyType)) {
            url = url + ruleConfig.getCashFlowUrl();
            riskParam.put("xds_type", "ConsumerFullCreditReport");
            riskParam.put("creat_time", customerCreditService.geXdsTime(ruleIn.getCustNo()));
            apiName = "TD-Loan";
        } else {
            url = url + ruleConfig.getCreditFlowUrl();
            apiName = "TD-Credit";
        }
        log.info(applyType + "规则1入参json:{}", riskParam.toJSONString());

        String apiResult = iExternalApiService.ruleRequest(riskParam, url, apiName);

        log.info(applyType + "规则1出参json:{}", apiResult, ruleIn.getCustNo());
        log.info(applyType + "规则1出参custNo:{}", ruleIn.getCustNo());

        ruleIn.setRecFlag(UserConstants.BUSINESS_NORMAL);
        ruleInService.updateRuleIn(ruleIn);

        //解析结果并返回
        JSONObject result = this.analysisRuleOut(apiResult, ruleIn.getCustNo(), ruleIn.getApplySerialNo(), ruleIn.getLoanSerialNo(), ruleIn.getOperType());
        //拒绝或者取消
        if (RiskConstants.RULE_RESULT_CLOSE.equals(result.get(RiskConstants.RULE_RESULT_DEAL_TYPE_KEY)) || RiskConstants.RULE_RESULT_REJECT.equals(result.get(RiskConstants.RULE_RESULT_DEAL_TYPE_KEY)) || RiskConstants.RULE_RESULT_REVOKE.equals(result.get(RiskConstants.RULE_RESULT_DEAL_TYPE_KEY))) {
            return result;
        }
        //下一步
        RuleNextDto ruleNextDTO = customerCreditService.getConsumerCreditData(ruleIn.getCustNo(), result.getString(RiskConstants.RULE_RESULT_NEED_REPORT), applyType);
        return this.riskRuleNextStep2(ruleNextDTO, applyType, serialNo, result.get(RiskConstants.RULE_TOKEN).toString(), result.get(RiskConstants.RULE_ENTRY_ID).toString());
    }

    public JSONObject riskRuleNextStep2(RuleNextDto ruleNextDTO, String applyType, String serialNo, String token, String entryId) {
        //参数加工
        Object ruleInCredit = step2ParamsLoader.initRuleInParam(ruleNextDTO, applyType, serialNo, token, entryId);

        RuleInNextStep ruleInNextStep = (RuleInNextStep) ruleInCredit;
        iRuleInNextStepService.insertRuleInNextStep(ruleInNextStep);

        if (ruleInCredit instanceof RuleInNextStepCrs) {
            NextStepCrs nextStepCrs = new NextStepCrs();
            BeanUtils.copyBeanProp(nextStepCrs, ruleInCredit);
            nextStepCrs.setNextStepId(ruleInNextStep.getId());
            iNextStepCrsService.insertNextStepCrs(nextStepCrs);
        }
        if (ruleInCredit instanceof RuleInNextStepXds) {
            NextStepXds nextStepXds = new NextStepXds();
            BeanUtils.copyBeanProp(nextStepXds, ruleInCredit);
            nextStepXds.setNextStepId(ruleInNextStep.getId());
            iNextStepXdsService.insertNextStepXds(nextStepXds);
        }


        RealNameAuth realNameAuth = new RealNameAuth();
        realNameAuth.setCustNo(ruleInNextStep.getCustNo());
        List<RealNameAuth> realNameAuths = iRealNameAuthService.selectRealNameAuthList(realNameAuth);

        JSONObject riskParam = JSONObject.parseObject(JSONObject.toJSON(ruleInCredit).toString());
        riskParam.put("runType", ruleConfig.getRunType());


        log.info(applyType + "规则2入参json:{}", riskParam.toJSONString());
        log.info(applyType + "规则2入参custNo:{}", ruleInNextStep.getCustNo());

        String url = ruleConfig.getUrl();
        String apiName = "";
        if (RuleConfig.RULE_TYPE_LOAN.equals(applyType)) {
            url = url + ruleConfig.getLoanNextStepUrl();
            apiName = "TD-Loan-Next-Step";
        } else {
            url = url + ruleConfig.getCreditNextStepUrl();
            apiName = "TD-Credit-Next-Step";
        }

        String apiResult = iExternalApiService.ruleRequest(riskParam, url, apiName);

        log.info(applyType + "规则2出参json:{}", apiResult);
        log.info(applyType + "规则2出参custNo:{}", ruleInNextStep.getCustNo());

        //解析结果并返回
        return this.analysisRuleOut(apiResult, realNameAuths.get(0).getUserId(), ruleInNextStep.getApplySerialNo(), ruleInNextStep.getLoanSerialNo(), ruleInNextStep.getOperType());
    }


    private JSONObject analysisRuleOut(String resultStr, String userId,
                                       String applySerialNo, String loanSerialNo, String operType) {

        JSONObject content = JSONObject.parseObject(resultStr);

        Date createTime = new Date();
        RuleOut ruleOut = new RuleOut();
        ruleOut.setState(UserConstants.BUSINESS_NORMAL);
        ruleOut.setDecisionEngineResult(resultStr);
        ruleOut.setCreateTime(createTime);
        ruleOut.setUpdateTime(createTime);
        ruleOut.setCustNo(userId);
        ruleOut.setApplySerialNo(applySerialNo);
        ruleOut.setLoanSerialNo(loanSerialNo);
        ruleOut.setOperType(operType);

        ruleOut.setSucc(content.getString("succ") == null ? null : content.getString("succ"));
        if ("false".equals(ruleOut.getSucc())) {
            ruleOut.setReasonDesc(content.get("msg") == null ? null : content.getString("msg"));
        }

        JSONObject contentData = content.getJSONObject("data");
        JSONObject envVariable = new JSONObject();
        String needReport = "";

        String finalDealTypeCode = "";
        if (null != contentData) {
            ruleOut.setEntryId(contentData.get("entryId") == null ? null : contentData.getString("entryId"));
            ruleOut.setGuardId(contentData.get("guardId") == null ? null : contentData.getString("guardId"));
            ruleOut.setToken(contentData.get("token") == null ? null : contentData.getString("token"));
            ruleOut.setReasonCode(contentData.get("reasonCode") == null ? null : contentData.getString("reasonCode"));
            ruleOut.setReasonDesc(contentData.get("reasonDesc") == null ? null : contentData.getString("reasonDesc"));
            ruleOut.setResonDetail(contentData.get("resonDetail") == null ? null : contentData.getString("resonDetail"));
            ruleOut.setFinalDealTypeCode(contentData.get("finalDealTypeCode") == null ? null : contentData.getString("finalDealTypeCode"));
            ruleOut.setFinalDealTypeName(contentData.get("finalDealTypeName") == null ? null : contentData.getString("finalDealTypeName"));
            ruleOut.setRiskLevel(contentData.get("riskLevel") == null ? null : contentData.getString("riskLevel"));
            ruleOut.setRiskBehaviorScore(contentData.get("riskBehaviorScore") == null ? null : contentData.getString("riskBehaviorScore"));
            ruleOut.setCloseReason(contentData.get("close_reason") == null ? null : contentData.getString("close_reason"));
            envVariable = contentData.getJSONObject("envVariable");
            if (null != envVariable) {
                ruleOut.setCustrvwResult(envVariable.getString("custrvwresult"));
                ruleOut.setLoan(envVariable.getString("loan"));
                //授信额度
                ruleOut.setFinalLoan(envVariable.getString("finalLoan"));
                //是否执行下一步
                needReport = Func.isNotEmpty(envVariable.get("needreport")) ? envVariable.get("needreport").toString() : "";
                ruleOut.setNeedReport(needReport);
                //模型等级
                ruleOut.setModelLevel(envVariable.getString("modellevel"));
                //测算额度
                ruleOut.setPreLine(envVariable.getString("preline"));
                //提额最终额度
                ruleOut.setLimitAdjust(envVariable.getString("limitadjust"));
                //渠道额度
                ruleOut.setChannelQuota(envVariable.getBigDecimal("channelquota"));
                //信用评级
                ruleOut.setCreditRating(envVariable.getString("creditrating"));
                //可主动发起提额
                ruleOut.setPromotion(envVariable.getString("getpromotion"));
                //授信评级
                ruleOut.setCreditmodellevel(envVariable.getString("creditmodellevel"));
            }

            JSONArray nodeResult = contentData.getJSONArray("nodeResult");
            if (null != nodeResult && nodeResult.size() > 0) {
                for (int i = 0; i < nodeResult.size(); i++) {
                    JSONObject node = nodeResult.getJSONObject(i);
                    if (null != node.get("nodeType") && "PolicyService".equals(node.getString("nodeType"))) {//如果是规则
                        RuleNodeResult ruleNodeResult = new RuleNodeResult();
                        ruleNodeResult.setState(UserConstants.BUSINESS_NORMAL);
                        ruleNodeResult.setCreateTime(createTime);
                        ruleNodeResult.setUpdateTime(createTime);

                        ruleNodeResult.setSucc(node.get("success") == null ? null : node.getString("success"));
                        ruleNodeResult.setEntryId(ruleOut.getEntryId());
                        ruleNodeResult.setDisplayName(node.get("displayName") == null ? null : node.getString("displayName"));
                        ruleNodeResult.setNodeId(node.get("nodeId") == null ? null : node.getString("nodeId"));
                        ruleNodeResult.setNodeType(node.get("nodeType") == null ? null : node.getString("nodeType"));
                        ruleNodeResult.setNodeName(node.get("nodeName") == null ? null : node.getString("nodeName"));
                        ruleNodeResult.setError(node.get("error") == null ? null : node.getString("error"));

                        JSONObject nodeResult2 = node.getJSONObject("result");
                        if (null != nodeResult2) {
                            ruleNodeResult.setReasonCode(nodeResult2.get("reasonCode") == null ? null : nodeResult2.getString("reasonCode"));
                            ruleNodeResult.setFinalScore(nodeResult2.get("finalScore") == null ? null : nodeResult2.getString("finalScore"));
                            ruleNodeResult.setPolicySetName(nodeResult2.get("policySetName") == null ? null : nodeResult2.getString("policySetName"));
                            ruleNodeResult.setFinalDealTypeCode(nodeResult2.get("finalDealType") == null ? null : nodeResult2.getString("finalDealType"));
                            if (nodeResult2.get("finalDealType") != null) {
                                finalDealTypeCode = nodeResult2.get("finalDealType").toString();
                            }
                            ruleNodeResult.setFinalDealTypeName(nodeResult2.get("finalDealTypeName") == null ? null : nodeResult2.getString("finalDealTypeName"));
                            ruleNodeResult.setFinalDealTypeGrade(nodeResult2.get("finalDealTypeGrade") == null ? null : nodeResult2.getString("finalDealTypeGrade"));
                            ruleNodeResultService.insertRuleNodeResult(ruleNodeResult);

                            JSONArray hitRules = nodeResult2.getJSONArray("hitRules");
                            if (null != hitRules && hitRules.size() > 0) {
                                for (int j = 0; j < hitRules.size(); j++) {
                                    JSONObject hit = hitRules.getJSONObject(j);
                                    RuleHit ruleHit = new RuleHit();
                                    ruleHit.setState(UserConstants.BUSINESS_NORMAL);
                                    ruleHit.setCreateTime(createTime);
                                    ruleHit.setUpdateTime(createTime);
                                    ruleHit.setCustNo(userId);
                                    ruleHit.setApplySerialNo(applySerialNo);
                                    ruleHit.setLoanSerialNo(loanSerialNo);
                                    ruleHit.setOperType(operType);

                                    ruleHit.setEntryId(ruleNodeResult.getEntryId());
                                    ruleHit.setNodeId(ruleNodeResult.getId() + "");
                                    ruleHit.setUuid(hit.get("uuid") == null ? null : hit.getString("uuid"));
                                    ruleHit.setName(hit.get("name") == null ? null : hit.getString("name"));
                                    ruleHit.setDealType(hit.get("dealType") == null ? null : hit.getString("dealType"));
                                    ruleHit.setRuleDetailDataList(hit.get("ruleDetailDataList") == null ? null : hit.getString("ruleDetailDataList"));
                                    ruleHitService.insertRuleHit(ruleHit);
                                }
                            }
                        }
                    }
                }
            }
        }

        if (Func.isEmpty(ruleOut.getFinalDealTypeCode())) {
            ruleOut.setFinalDealTypeCode(finalDealTypeCode);
        }

        ruleOut.setExpiryDate(envVariable.getString("outputexpirydate"));
        ruleOut.setNeedbindcardnum(envVariable.getString("needbindcardnum"));
        log.info("MARK-------------->");
        ruleOut.setAwardQualified(envVariable.getString("awardqualified"));
        ruleOutService.insertRuleOut(ruleOut);

        /**
         * finalDealTypeCode=Reject   拒绝
         * finalDealTypeCode=NextStep 下一步
         * finalDealTypeCode=Close 关闭
         * finalDealTypeCode=Accept 通过
         */
        JSONObject result = new JSONObject();
        result.put(RiskConstants.RULE_RESULT_DEAL_TYPE_KEY, Func.isEmpty(ruleOut.getFinalDealTypeCode()) ? finalDealTypeCode : ruleOut.getFinalDealTypeCode());
        result.put(RiskConstants.RULE_RESULT_CLOSE_REASON, ruleOut.getCloseReason());
        result.put(RiskConstants.RULE_RESULT_NEED_REPORT, needReport);
        result.put(RiskConstants.RULE_TOKEN, Func.isEmpty(ruleOut.getToken()) ? "" : ruleOut.getToken());
        result.put(RiskConstants.RULE_ENTRY_ID, Func.isEmpty(ruleOut.getEntryId()) ? "" : ruleOut.getEntryId());

        //授信额度
        result.put(RiskConstants.RULE_RESULT_FINAL_LOAN_KEY, StringUtils.isNotBlank(ruleOut.getFinalLoan()) ? ruleOut.getFinalLoan() : "0");

        //提现冻结期
        result.put(RiskConstants.RULE_RESULT_APPLY_FREEZE, envVariable.get("applyfreezedate"));
        //授信冻结期
        result.put(RiskConstants.RULE_RESULT_LOAN_FREEZE, envVariable.get("loanfreezedate"));
        //征信有效期
        result.put(RiskConstants.RULE_CREDIT_EXPIRY_DATE, envVariable.get("outputexpirydate"));
        //测算额度
        result.put(RiskConstants.RULE_PASS_PRE_LINE, ruleOut.getPreLine());
        //模型评级
        result.put(RiskConstants.RULE_MODEL_LEVEL, ruleOut.getModelLevel());
        //最终额度
        result.put(RiskConstants.RULE_RAISE_PASS_ADJUST_LIMIT, ruleOut.getLimitAdjust());
        //渠道额度
        result.put(RiskConstants.RULE_RAISE_PASS_CHANNEL_LIMIT, ruleOut.getChannelQuota());
        //产品信用评级
        result.put(RiskConstants.RULE_CREDIT_RATING, ruleOut.getCreditRating());
        //主动提额
        result.put(RiskConstants.RULE_PROMOTION, ruleOut.getPromotion());
        result.put(RiskConstants.RULE_CREDIT_MODEL_LEVEL, ruleOut.getCreditmodellevel());
        //客户需要绑定的有效银行卡数
        result.put(RiskConstants.RULE_NEED_BIND_CARD_NUM, ruleOut.getNeedbindcardnum());

        //奖励分组
        result.put(RiskConstants.RULE_AWARD_QUALIFIED, ruleOut.getAwardQualified());


        //取消
        if (!"9000".equals(ruleOut.getReasonCode())) {
            result.put(RiskConstants.RULE_RESULT_DEAL_TYPE_KEY, RiskConstants.RULE_RESULT_REVOKE);
        }

        return result;
    }


}
